<template>
<div>
  <el-row>
    <el-col v-for="shopping in shoppings" :span="6">
      <el-card style="margin: 20px ;width: 300px">
        <div style="width: 260px;height: 250px">
          <img :src="shopping.img"  alt="jpg" style="margin: 0 auto;object-fit: cover; width: 100%;height: 100%;">
        </div>
        <ul>

          <li class="price ">
            <div style="float: left;">热卖价</div>
            <div class="priceNum" style="float: left;margin-left: 40px">￥{{shopping.shoppingPrice.toFixed(2)}}</div>
          </li>
          <li>
            <div style="float: left;">名称</div>
            <div  style="float: left;margin-left: 60px">{{shopping.shoppingName}}</div>
          </li>
          <li>
           <div class="stores" style="font-size: 14px;color: #afafaf">
             <el-icon style="color: #e87f7f;float: left;"><OfficeBuilding /></el-icon>
             <div style="margin-left: 15px;color: #9b9b9b;font-size: 12px;float: left">
               {{shopping.vendor}}
             </div>
           </div>
          </li>
          <li style="margin-top: 10px">
              <div class="inputNum" style="float: left;">
                <el-input-number v-model="shopping.shoppingNum" :min="1" :max="shopping.maxValue" style="width: 115px"  />
              </div>
              <div class="addToShoppingCar">
                <el-button @click="addShoppingCar(shopping)">加入购物车</el-button>
              </div>
          </li>
        </ul>

      </el-card>
    </el-col>
  </el-row>
  <el-tooltip class="item" effect="dark" content="加入购物车" placement="left">
    <div class="shoppingCar" @click="drawer=!drawer" >
      <el-avatar style="background-color:#fcfafa;object-fit: cover; width: 100%;height: 100%;" :src="require('@/assets/shoppingCar.png')" ></el-avatar>
    </div>
  </el-tooltip>

  <el-tooltip class="item" effect="dark" content="我要预定" placement="left">
    <div class="willShoppingCar" @click="prodrawer=!prodrawer" >
      <el-avatar style="background-color:#fcfafa;object-fit: cover; width: 100%;height: 100%;" :src="require('@/assets/probuy.png')" ></el-avatar>
    </div>
  </el-tooltip>

  <el-drawer v-model="drawer" size="23%" :direction="'rtl'">
    <template #header>
      <h3>我的购物车</h3>
    </template>
    <template #default>

    <NoShoppingSlot>
    <div  v-if="this.order.shoppingList.length">
      <span class="priceNum" style="margin-bottom: 10px;">已选 {{order.shoppingList.length}} 件，合计￥ {{order.totalPay.toFixed(2)}}</span>
    </div>
      <el-card class="finalShopping" v-for="shopping in order.shoppingList">
          <span style="display: inline-block;">{{shopping.shoppingName}}*{{shopping.shoppingNum}}  </span>
          <span style="display: inline-block;margin-left: 30px">{{(shopping.shoppingPrice*shopping.shoppingNum).toFixed(2)}}</span>
      </el-card>
    </NoShoppingSlot>

    </template>
    <template #footer>
      <div style="margin:100px 50px" v-if="this.order.shoppingList.length">
        <el-button @click="cancelClick">再看看</el-button>
        <el-button style="margin-left:50px " type="primary" @click="buyShopping">下单</el-button>
      </div>
    </template>
  </el-drawer>

<!--预定的商品-->
  <el-drawer v-model="prodrawer" size="28%" :direction="'rtl'">
    <template #header>
      <h3>预定商品</h3>
    </template>
    <template #default>

      <span class="priceNum" style="margin-bottom: 10px;">已选 {{totalNum}} 件，合计￥ {{totalCost.toFixed(2)}}</span>

      <el-card class="finalShopping"  v-for="(item, index) in proOrderShoppingList" :key="index" >
        <div>
          <el-select style="width:150px;margin-right: 10px" v-model="proOrderShoppingList[index].shoppingCode" placeholder="请选择商品" @change="handleSelectionChange(index)">
            <el-option v-for="option in availableShoppings(index)" :key="option.shoppingCode" :label="option.shoppingName" :value="option.shoppingCode"></el-option>
          </el-select>
          <el-input-number v-model="proOrderShoppingList[index].shoppingNum" :min="1" :max="1000" style="width: 115px"  />
        </div>
      </el-card>
      <el-button v-if="proOrderShoppingList.length<8" style="margin: 30px auto" @click="addSelect">新增商品</el-button>
      <div style="margin:100px 20px" v-if="totalNum">
        <el-button @click="prodrawer=false">再看看</el-button>
        <el-button style="margin-left:50px " type="primary" @click="buyProShopping">下单</el-button>
      </div>

    </template>

  </el-drawer>
  <div>
    <!--  下单的确认界面 显示订单的所有信息-->
    <!--  弹窗表单-->
    <!--  <el-dialog v-model="isShowForm"  width="600px" draggable class="formclass">-->
    <!--    <el-form-->
    <!--        label-width="100px"-->
    <!--        :model="order"-->
    <!--        :rules="rule"-->
    <!--        ref="FORM"-->
    <!--    >-->
    <!--      <el-form-item label="客户姓名" prop="username">-->
    <!--        <el-input v-model="userName"  />-->
    <!--      </el-form-item>-->
    <!--      <el-form-item label="联系方式" prop="tele">-->
    <!--        <el-input v-model="form.tele" />-->
    <!--      </el-form-item>-->
    <!--      <el-form-item label="常用地址" prop="loc">-->
    <!--        <el-input :readonly="true" v-model="form.loc" />-->
    <!--      </el-form-item>-->
    <!--      <el-row>-->
    <!--        <el-col :span="10">-->
    <!--          <el-form-item label="省" prop="province">-->
    <!--            <el-select v-model="form.province" @change="getProvinces" filterable placeholder="请选择省份" fit-input-width="true"-->
    <!--                       style="width: 120px" prop="province">-->
    <!--              <el-option-->
    <!--                  v-for="item in locValue.provinces"-->
    <!--                  :key="item.provinceId"-->
    <!--                  :label="item.provinceName"-->
    <!--                  :value="item.provinceName">-->
    <!--              </el-option>-->
    <!--            </el-select>-->
    <!--          </el-form-item>-->
    <!--        </el-col>-->

    <!--        <el-col :span="10">-->
    <!--          <el-form-item label="市" prop="city">-->
    <!--            <el-select v-model="form.city" @change="getCities" placeholder="请选择市"  style="width: 150px" prop="city">-->
    <!--              <el-option-->
    <!--                  v-for="item in this.locValue.cities"-->
    <!--                  :key="item.cityId"-->
    <!--                  :label="item.cityName"-->
    <!--                  :value="item.cityName">-->
    <!--              </el-option>-->
    <!--            </el-select>-->
    <!--          </el-form-item>-->
    <!--        </el-col>-->
    <!--        <el-col :span="10">-->
    <!--          <el-form-item label="区" prop="religion" >-->
    <!--            <el-select v-model="form.religion"  @change="getRegions" placeholder="请选择区"  style="width: 150px;" prop="religion">-->
    <!--              <el-option-->
    <!--                  v-for="item in locValue.religions"-->
    <!--                  :key="item.regionId"-->
    <!--                  :label="item.regionName"-->
    <!--                  :value="item.regionName">-->
    <!--              </el-option>-->
    <!--            </el-select>-->
    <!--          </el-form-item>-->
    <!--        </el-col >-->
    <!--      </el-row>-->
    <!--      <el-form-item label="详细地址" prop="other" >-->
    <!--        <el-input style="width: 250px;margin-top: 10px" @change="getOthers" placeholder="请输入具体地址" prop="other" v-model="form.other"></el-input>-->
    <!--      </el-form-item>-->



    <!--      <el-form-item>-->
    <!--        <el-button type="primary" @click="onSubmit">提交</el-button>-->
    <!--        <el-button @click="cancelExpert('FORM')">取消</el-button>-->
    <!--      </el-form-item>-->
    <!--    </el-form>-->

    <!--  </el-dialog>-->


  </div>
</div>
</template>

<script>
import cloneDeep from 'lodash/cloneDeep'
import store from '@/store/index'
import {Delete, Edit, Search, ShoppingCartFull, Van,OfficeBuilding} from '@element-plus/icons-vue';
import NoShoppingSlot from "@/views/user/NoShopping-Slot";
import {request_user, request_warehouse} from "@/util/request";
import {getDatetime} from "@/util/Utils";
import Pop from "@/views/user/Pop";

export default {
  name: "Shopping",
  components: {Pop, NoShoppingSlot},
  data(){
    return{
      prodrawer:false,
      isShowForm:true,
      userName:store.state.user.username,
      order:{
        status:'可分配订单',
        type:'',
        recv:store.state.user.uid,
        loc:store.state.user.loc,
        tele:store.state.user.tele,
        totalPay:0,
        shoppingList:[],
        newShoppingList:[],
        note:'',
        arriveTime:'',
        buyTime:''
      },
      proOrderShoppingList:[
          {shoppingCode:null,
            shoppingNum:1}
      ],//选择框
      shoppingTable:[],
      Icon: {Delete, Edit, Search, Van,ShoppingCartFull,OfficeBuilding},
    shoppings:[
      {
        shoppingCode: "G690BJMBXYW9BG7092925865797",
        shoppingName: "爆浆面包香芋味",
        shoppingPrice: 6.00,
        manufacturers: "南宁市西乡塘区屯里村89号",
        expirationDate: "120天",
        vendor: "金添旺食品有限责任公司",
        note: "无"
      },
    ],
      num:0,
      drawer:false
    }
  },
  methods:{
    //检查是不是符合缺货的标准 list1是缺货商品列表，list2是库存商品列表
   checkMaxValue(list1, list2) {
  for (const item of list1) {
    const matchingItem = list2.find((obj) => obj.shoppingCode === item.shoppingCode);
    if (matchingItem && item.shoppingNum < matchingItem.maxValue) {
      return false;
    }
  }
  return true;
},

    //添加选择商品后的动作
    addSelect(){
      this.proOrderShoppingList.push(
          {shoppingCode:null ,
            shoppingNum:1});
    },
    //每次选择之后，下一个select会减少这个选项
    availableShoppings(index) {
      const selectedCodes = this.proOrderShoppingList.map(item => item.shoppingCode);
      return this.shoppings.filter(item => !selectedCodes.includes(item.shoppingCode) || item.shoppingCode === this.proOrderShoppingList[index].shoppingCode);
    },
    //每次选择之后就把它加入列表
    handleSelectionChange(index){
      const selectedShoppingCode = this.proOrderShoppingList[index].shoppingCode;
      const selectedShopping = this.shoppings.find(item => item.shoppingCode === selectedShoppingCode);
      if (selectedShopping) {
        const updatedShopping = cloneDeep(this.proOrderShoppingList[index]);
        updatedShopping.shoppingPrice = selectedShopping.shoppingPrice;
        updatedShopping.shoppingName =selectedShopping.shoppingName
        this.proOrderShoppingList.splice(index, 1, updatedShopping);
      }
      console.log(this.proOrderShoppingList)
    },
//取消动作
    cancelClick(){
     this.drawer=false
      this.prodrawer=false
    },

    //预订下单，这是缺货单
    buyProShopping(){

      this.order.buyTime=getDatetime("time")
      this.order.arriveTime=this.handleDayTime(getDatetime("day"))
        this.order.shoppingList =cloneDeep( this.proOrderShoppingList)
        this.order.type="缺货单"
        //如果不满足缺货条件就可以直接结束了
        if(!this.checkMaxValue(this.order.shoppingList,this.shoppings)){
          this.$message({
            message: '您所购买的商品库存有货，请直接加入购物车下单即可！',
            type: 'error'
          });
          this.cancelClick()
          this.proOrderShoppingList=[{shoppingCode:null,
            shoppingNum:1}]
          return;
        }

      request_user.post("order/lack",this.order).then(res=>{
        console.log(res.data)
        if(res.data.code===200){
          this.$message({
            message: '预订成功！',
            type: 'success'
          });
          this.cancelClick()
          this.order.shoppingList.length=0
          this.proOrderShoppingList= [{shoppingCode:null,
            shoppingNum:1}]
        }else {
          this.$message({
            message: '预订失败，请稍后再试！',
            type: 'error'
          });
        }
      })
    },
    //点击后下单  普通订单下单
    buyShopping(){

        this.order.buyTime=getDatetime("time")
        this.order.arriveTime=this.handleDayTime(getDatetime("day"))
        this.order.type="普通订单"
        request_user.post("order/add",this.order).then(res=>{
          console.log(res.data)
          if(res.data.code===200){
            this.$message({
              message: '下单成功！',
              type: 'success'
            });
            this.cancelClick()
            this.order.shoppingList.length=0
          }else {
            this.$message({
              message: '下单失败，请稍后再试！',
              type: 'error'
            });
          }
        })
    },
    //得到订单里面的总价
    handleTotalPay(item){
      this.order.totalPay +=item.shoppingPrice*item.shoppingNum
    },
    //生成订单里面的arriveTime
    handleDayTime(current){
      let arrs= current.split('-')
      arrs[2]=String(Number(arrs[2])+Math.ceil(Math.random()*3))
      return arrs.join('-')
    },
    //添加到购物车成功后的提示
    addsuccess(shopping,num) {
      this.$notify({
        title: '添加成功',
        dangerouslyUseHTMLString: true,
        message: '已添加 '+'&nbsp;'+'<strong>' +shopping+" x "+num+'</strong>'+'&nbsp;'+" 到购物车",
        type: 'success'
      });
    },
    //添加购物车的动作
    addShoppingCar(shopping){

    //  this.order.shoppingList.push(shopping)
      //对相同的商品进行合并
      //第一件
      if(this.order.shoppingList.length===0){
        this.handleSameShoppping(shopping)
      }else{
        //相同的第二件 应该只有一件与之前的相同
        let sameShopping = this.order.shoppingList.filter((item)=>item.shoppingCode===shopping.shoppingCode);
        //合并拿到的新商品和过滤出来这个
        if(sameShopping.length!==0){
          //先把先相同的拿出来
          this.order.shoppingList=this.order.shoppingList.filter((item)=>item.shoppingCode!==shopping.shoppingCode)
          //如果有相同商品的话，合并数量
          sameShopping[0].shoppingNum +=shopping.shoppingNum
          //加进去
          this.order.shoppingList.push(sameShopping[0])
        }else{
          //如果没有相同的商品的话，按照第一件处理，直接加工后加进去
          this.handleSameShoppping(shopping)
        }
      }
      this.addsuccess(shopping.shoppingName,shopping.shoppingNum)
      this.order.totalPay=0
      this.order.shoppingList.forEach(this.handleTotalPay)

    },

    handleSameShoppping(item){
      //对同类型商品整合后的最终商品对象，是后端所需要的商品属性
      let shoppingItem={
            shoppingCode:'',
            shoppingName: "",
            shoppingPrice: 0.00,
            shoppingNum:0
      }
      shoppingItem.shoppingName=item.shoppingName
      shoppingItem.shoppingPrice=item.shoppingPrice
      shoppingItem.shoppingCode=item.shoppingCode
      shoppingItem.shoppingNum+=item.shoppingNum
      this.order.shoppingList.push(shoppingItem)
    },

    handleMaxValue(){

// 存储所有的请求
      const requests = [];

// 遍历shoppingList中的每个shopping对象
      for (let i = 0; i < this.shoppings.length; i++) {
        const shopping = this.shoppings[i];

        // 发起异步请求并将请求添加到requests数组中
        const request=  request_warehouse.post('inventory/queryInventoryInfo',{
          warehouseId:1,
          code:shopping.shoppingCode,
          pageNow:0,
          pageSize:100

        });
        requests.push(request);
      }
// 等待所有请求完成
      Promise.all(requests)
          .then(responses => {
            // 遍历响应并将maxValue赋值给对应的shopping对象
            for (let i = 0; i < responses.length; i++) {
              const response = responses[i];
              console.log(response.data)
              const shopping = this.shoppings[i];
              const maxValue = response.data.data.rowData[0].num;
              shopping.maxValue = maxValue;
            }
          })
          .catch(error => {
            console.error('请求出错:', error);
          });
    }

  },
  //展示所有商品信息
  beforeMount() {
      this.shoppings=store.state.shoppings
      this.handleMaxValue()
  },
  computed: {
    totalCost() {
      return this.proOrderShoppingList.reduce((total, item) => {
        const shopping = this.shoppings.find(option => option.shoppingCode === item.shoppingCode);
        if (shopping) {
          return total + shopping.shoppingPrice * item.shoppingNum;
        }
        return total;
      }, 0);
    },
    totalNum(){
      return this.proOrderShoppingList.reduce((total,item)=>{
          if(item.shoppingCode){
           return  total + 1
          }
          return total
      },0)
    }
  }

}
</script>

<style scoped>
ul{

}
li{
  overflow: auto;
  list-style: none;
  margin: 8px auto;
  font-size: 15px;
}

.price{
  color: rgb(215, 50, 55);
}
.priceNum{

  margin-left: 4px;
  vertical-align: baseline;
  text-align: left;
  line-height: 25px;
  font-family: PingFangSC-Medium;
  font-size: 18px;
  color: #fd3f31;
}
.finalShopping{
  font-size: 18px;
  margin: 10px auto;
}
.shoppingCar{
  height: 50px;width: 50px;
 display: flex;
  position: sticky;
  right: 40px;
  justify-content: flex-end;
  margin-left: auto;

  bottom: 140px;
}
.willShoppingCar{
  height: 50px;width: 50px;
  display: flex;
  position: sticky;
  right: 40px;
  justify-content: flex-end;

  margin-left: auto;
  bottom: 70px;
}
.shoppingCar:hover{
  cursor: pointer;
}
</style>